/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.helper;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import org.domain.*;

/**
 *
 * @author davidsciacchettano
 */
public class RequestCatalog {
    private String xmlRequest;
    private String urlRequest = "http://localhost:9080/RetailServiceCatalogWsdlService/RetailServiceCatalogWsdlPort";
    private HttpURLConnection conn;    
    private int requestResponse;
    private ArrayList<Item> items = new ArrayList<Item>();
    
    public ArrayList<Item> getItems() {
        return items;
    }
    
    public RequestCatalog() {
        this.createXmlRequest();
        this.createHttpRequest();
        this.requestResponse = this.sendRequest();
        
        //make sure the request was processed properly        
        if(this.requestResponse == 200) {
            this.pareseXml();
        } else {
            System.out.println("Response Code:  " + this.requestResponse);
            System.exit(-1);
        }
    }
    
    
    /*
     * Method to create an XML request to obtain the catalog.
     */
    public void createXmlRequest() {
        xmlRequest = "<soapenv:Envelope xsi:schemaLocation=\"http://schemas.xmlsoap.org/soap/envelope/ http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ret=\"http://j2ee.netbeans.org/wsdl/RetailServiceCatalogWsdl\">" +
            "<soapenv:Body>" +
                "<ret:RetailServiceCatalogWsdlOperation>" +
                    "<Request>blah</Request>" +
                "</ret:RetailServiceCatalogWsdlOperation>" +
            "</soapenv:Body>" +
            "</soapenv:Envelope>";
    }
    
    /*
     * Method to create an HTTP Request.
     */
    public void createHttpRequest() {
        try {
            conn = (HttpURLConnection) new URL(urlRequest).openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
            
            conn.setDoInput(true);
            conn.setDoOutput(true);
            
        }catch(IOException ioe) {
            ioe.printStackTrace();
        }
    }
    
    /*
     * Method to send request to the Bpel Module.
     */
    public int sendRequest() {
        int responseCode = -1;
        
        try {
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            dos.writeBytes(xmlRequest);
            dos.flush();
            dos.close();
            
            //wait for the response and retun the response code
            responseCode =  conn.getResponseCode();
        } catch(IOException ioe) {
            ioe.printStackTrace();
        }
        
        return responseCode;
    }
    
    /*
     * Parse response XML and return an array of Items.
     */
    public void pareseXml() {
        Item tmpItem;        
        Document doc = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db;
        InputStream res = null;
        
        //get the return value of the 
        try {
            res = conn.getInputStream();
        } catch(IOException ioe) {
            ioe.printStackTrace();
        }
        
        
        //build a document factory to step thru the xml return documnet
        try {
            db = dbf.newDocumentBuilder();
            doc = db.parse(res);
        } catch(ParserConfigurationException pce) {
            pce.printStackTrace();
        } catch(SAXException se) {
            se.printStackTrace();
        } catch(IOException ioe) {
            ioe.printStackTrace();
        }
        
        doc.getDocumentElement().normalize();
        
        //get the <return> eleemtns
        NodeList returnList = doc.getElementsByTagName("return");
        
        //loop trough the returned nodes
        for(int i = 0; i < returnList.getLength(); i++) {
            if(i < 9) {
            //get each return node
                Node returnNode = returnList.item(i);

                //get the children of the return tag and get the individual values
                NodeList individualReturnNode = returnNode.getChildNodes();

                tmpItem = new Item();

                //set the individual child tags to the item class
                tmpItem.setId(i);

                for(int x = 0; x < individualReturnNode.getLength(); x++) {

                    if(individualReturnNode.item(x).getNodeName().equals("manufacturerName")) {
                        tmpItem.setManufacturer(individualReturnNode.item(x).getChildNodes().item(0).getNodeValue());
                    }

                    if(individualReturnNode.item(x).getNodeName().equals("productType")) {
                        tmpItem.setProduct(individualReturnNode.item(x).getChildNodes().item(0).getNodeValue());
                    }

                    if(individualReturnNode.item(x).getNodeName().equals("quantity")) {
                        tmpItem.setQuantity(Integer.parseInt(individualReturnNode.item(x).getChildNodes().item(0).getNodeValue()));
                    }

                    if(individualReturnNode.item(x).getNodeName().equals("unitPrice")) {
                        tmpItem.setPrice(Float.parseFloat(individualReturnNode.item(x).getChildNodes().item(0).getNodeValue()));
                    }
                }
            

            /*
            tmpItem.setManufacturer(individualReturnNode.item(0).getChildNodes().item(0).getNodeValue());
            tmpItem.setProduct(individualReturnNode.item(1).getChildNodes().item(0).getNodeValue());
            tmpItem.setQuantity(Integer.parseInt(individualReturnNode.item(2).getChildNodes().item(0).getNodeValue()));
            tmpItem.setPrice(Float.parseFloat(individualReturnNode.item(3).getChildNodes().item(0).getNodeValue()));
            **/
            
            //test
            //System.out.println("\nItem: " + individualReturnNode.item(1).getChildNodes().item(0));
            
            //add to the item array list
            items.add(tmpItem);
            }
        }                
    }
    
    public static void main(String args[]) {
        RequestCatalog rc = new RequestCatalog();
        
        ArrayList<Item> items = rc.getItems();
        
        if(items != null) {
        
            System.out.println("Size:  " + items.size());
            for(int x = 0; x < items.size(); x++) {
                System.out.println("Item:  " + items.get(x));
            }
        } else {
            System.out.println("Null item array");
        }
    }
    
}
